package com.idol.config;

import com.idol.pojo.Configeration;
import com.idol.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * SQL 配置文件解析类
 *
 * @author Supreme_Sir
 * @version 1.0
 * @className XMLMapperBuilder
 * @description
 * @date 2020/9/26 15:45
 **/
public class XMLMapperBuilder {
    private Configeration configeration;
    public XMLMapperBuilder(Configeration configeration) {
        this.configeration = configeration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String nameSpace = rootElement.attributeValue("nameSpace");

        // 获取根节点下所有一级子节点
        List<Element> sqlElement = rootElement.elements();

        for (Element element : sqlElement) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("parameterType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement(id, paramterType, resultType, sqlText);
            String mappedStatementName = nameSpace + "." + id;
            this.configeration.putMappedStatement(mappedStatementName, mappedStatement);
        }
    }
}
